// 负责上传构建后的项目到后台网站

const Client = require('ftp')
const fs = require('fs')
const path = require('path')
const readline = require('readline')
const ora = require('ora')

const dirPath = path.join(__dirname, './dist')
const localFiles = [] // 本地文件
let localFileLength = 0 // 上传文件个数
let uploadTime = 0 // 上传耗时
let client = null
let ftpName = ''
let ftpPassword = ''

const uploadingFile = () => {
	return new Promise((resolve, reject) => {
		localFiles.forEach(file => {
			client.put(`${dirPath}/${file.fileName}`, `./kmhome/${file.fileName}`, err => {
				if (err) throw err
				localFileLength--
			})
		})
		let timer = setInterval(() => {
			if (localFileLength === 0) {
				clearInterval(timer)
				console.log(`用时：${uploadTime}s`)
				resolve()
			}
			uploadTime++
		}, 1000)
	})
}

const readFilesAndUpload = async () => {
	const progress01 = ora('读取 dist 目录...')
	progress01.start()
	await new Promise((resolve, reject) => {
		fs.readdir('./dist', { withFileTypes: true }, (err, files) => {
			if (err) throw err
			files.forEach(file => {
				fs.readFile(`./dist/${file.name}`, (err, data) => {
					if (err) throw err
					localFiles.push({
						fileName: file.name,
						fileData: data
					})
					localFileLength = localFiles.length
				})
			})
			// 轮询到读取结束
			let timer = setInterval(() => {
				if (localFileLength === localFiles.length) {
					clearInterval(timer)
					resolve()
				}
			}, 1000)
		})
	})
	progress01.stop()
	console.log('文件读取完毕!')

	const progress02 = ora('请求连接 FTP 服务...')
	progress02.start()

	client = new Client()

	const connectionProperties = {
		host: '39.105.219.37',
		user: ftpName,
		password: ftpPassword,
		port: 21
	}

	client.on('ready', () => {
		progress02.stop()
		console.log('FTP 成功连接!')

		const progress03 = ora('清空 kmhome 目录中...')
		progress03.start()

		client.rmdir('kmhome', true, err => {
			// 没有就直接继续
			if (err) {
			}
			progress03.stop()
			// 再创建 kmhome
			const progress04 = ora('新创建 kmhome 文件夹...')
			progress04.start()
			client.mkdir('kmhome', true, () => {
				progress04.stop()
				console.log('新建 kmhome!')

				const progress05 = ora('上传文件中...')
				progress05.start()

				uploadingFile()
					.then(() => {
						console.log(`上传完毕!`)
						progress05.stop()
						client.end()
					})
					.catch(err => {
						console.log(err)
						client.end()
					})
			})
		})
	})

	client.connect(connectionProperties)
}

const getFTPConfigReadLine = readline.createInterface({
	input: process.stdin,
	output: process.stdout
})

getFTPConfigReadLine.question('请输入 FTP 名称:', answer => {
	ftpName = answer.trim()
	getFTPConfigReadLine.question('请输入 FTP 密码:', answer => {
		ftpPassword = answer.trim()
		getFTPConfigReadLine.close()
		// 开始读取本地文件并上传
		readFilesAndUpload()
	})
})
